<!--店铺管理-->
<script setup lang="ts">
import {AxiosPromise} from "axios";
import lodash from 'lodash-es'

defineOptions({
  name: "Loss",
  inheritAttrs: false,
});

import {
	getLossPage,
	getLossForm,
	saveLoss,
	deleteLoss,
    importLoss,
    exportLoss,
    getNextCode
} from "@/api/loss";
import {getDictOptions} from "@/api/dict";

import { LossQuery, LossForm } from "@/api/loss/types";
import {listRoleOptions} from "@/api/role";
import {ElLoading, UploadFile} from "element-plus";
import 'element-plus/theme-chalk/el-loading.css';

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);
const lossDictList = ref<OptionType[]>();

const queryParams = reactive<LossQuery>({
  pageNum: 1,
  pageSize: 20,
});

const lossList = ref<[]>();
const roleList = ref<OptionType[]>();

const dialog = reactive<DialogOption>({
  visible: false,
});

const importDialog = reactive<DialogOption>({
  title: "损失细类导入",
  visible: false,
});

const excelFile = ref<File>();
const excelFilelist = ref<File[]>([]);

const formData = reactive<LossForm>({});

const rules = reactive({
  lossCode: [{ required: true, message: "请选择损失原因", trigger: "blur" }],
  detailCode: [{ required: true, message: "请输入损失原因细则编码", trigger: "blur" }],
  detailName: [{ required: true, message: "请输入损失原因细则名称", trigger: "blur" }],
  roleId: [{ required: true, message: "请选择角色", trigger: "blur" }],
});

/**
 * 查询
 */
function handleQuery() {
  loading.value = true;
  getLossPage(queryParams)
    .then(({ data }) => {
      lossList.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/**
 * 打开字典类型表单弹窗
 *
 * @param dicTypeId 字典类型ID
 */
async function openDialog(dicTypeId?: number) {
  await getRoleOptions();
  await getDictOptionList()
  dialog.visible = true;
  if (dicTypeId) {
    dialog.title = "修改损失细类";
    getLossForm(dicTypeId).then(({ data }) => {
      Object.assign(formData, data);
      if (formData.roleId !== undefined) {
        formData.roleId = +formData.roleId
      }
	  	if (formData.roleId) {
			  changeRole(formData.roleId)
			}
    });
  } else {
    dialog.title = "新增损失细类";
  }
}

/**
 * 字典类型表单提交
 */
function handleSubmit() {
  dataFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      loading.value = false;
		saveLoss(formData)
		  .then(() => {
			ElMessage.success("保存成功");
			closeDialog();
			handleQuery();
		  })
		  .finally(() => (loading.value = false));
	}
  });
}

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}


/**
 * 重置表单
 */
function resetForm() {
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();

  formData.id = undefined;
}

/**
 * 删除字典类型
 */
function handleDelete(dictTypeId?: number) {
  const dictTypeIds = [dictTypeId || ids.value].join(",");
  if (!dictTypeIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteLoss(dictTypeIds).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

const dictDataDialog = reactive<DialogOption>({
  visible: false,
});

/**
 * 获取角色下拉列表
 */
async function getRoleOptions() {
  listRoleOptions().then((response) => {
    roleList.value = response.data;
  });
}

/** 打开导入弹窗 */
async function openImportDialog() {
  importDialog.visible = true;
}

/**
 * Excel文件change事件
 *
 * @param file
 */
function handleExcelChange(file: UploadFile) {
	if (file.size !== undefined) {
		if (file.size > 20*1024*1024) {
			ElMessage.warning("上传文件大小已经超过20M，请尝试拆分成多个文件再上传");
			return false
		}
	}
  if (!/\.(csv|xlsx|xls|XLSX|XLS|CSV)$/.test(file.name)) {
    ElMessage.warning("上传Excel只能为xlsx、xls、csv格式");
    excelFile.value = undefined;
    excelFilelist.value = [];
    return false;
  }
  excelFile.value = file.raw;
}

/** 导入损失细类提交 */
function handleLossImport() {
  if (!excelFile.value) {
    ElMessage.warning("上传Excel文件不能为空");
    return false;
  }
  const importLoading = ElLoading.service({
    lock: true,
    text: '导入中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  importLoss(excelFile.value).then((response) => {
    importLoading.close()
    ElMessage.success(response.data);
    closeImportDialog();
    resetQuery();
  });
}

/**  关闭导入弹窗 */
function closeImportDialog() {
  importDialog.visible = false;
  excelFile.value = undefined;
  excelFilelist.value = [];
}

/** 导出标准账单配置 */
function handleLossExport() {
  exportLoss().then((response: any) => {
    const blob = new Blob([response.data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
    });
    const a = document.createElement("a");
    const href = window.URL.createObjectURL(blob); // 下载的链接
    a.href = href;
    a.download = decodeURI(
            response.headers["content-disposition"].split(";")[1].split("=")[1]
    ); // 获取后台设置的文件名称
    document.body.appendChild(a);
    a.click(); // 点击导出
    document.body.removeChild(a); // 下载完成移除元素
    window.URL.revokeObjectURL(href); // 释放掉blob对象
  });
}

function changeLossCode(lossCode?: string) {
  if (lossCode !== undefined && lossCode !== '') {
    getNextCode(lossCode).then(response => {
      formData.detailCode = response.data.detailCode
      formData.lossExplain = response.data.lossExplain
			const filterLoss = lodash.find(lossDictList.value, ['value', lossCode])
			formData.lossName = filterLoss.label
    })
  }
}

function changeRole(roleId: number) {
	const role = lodash.find(roleList.value, ['value', roleId])
	if (role) {
	  formData.orderStatusName = "待" + role.label + "处理"
	}
}

async function getDictOptionList() {
	getDictOptions('loss').then((response) => {
		lossDictList.value = response.data;
	});
}

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="损失细类名称" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="损失细类名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery()"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetQuery()"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between">
          <div>
            <el-button
              v-hasPerm="['sys:loss:save']"
              type="success"
              @click="openDialog()"
              ><i-ep-plus />新增</el-button
            >
            <el-button
              type="danger"
              :disabled="ids.length === 0"
              @click="handleDelete()"
			  			v-hasPerm="['sys:loss:delete']"
              ><i-ep-delete />删除</el-button
            >
          </div>
          <div>
              <el-button class="ml-3" @click="openImportDialog"
              ><template #icon><i-ep-top /></template>导入</el-button>
              <el-button class="ml-3" @click="handleLossExport">
                <template #icon><i-ep-download /></template>导出</el-button>
          </div>
        </div>
      </template>
      <el-table
        size="small"
        :height="lossList && lossList.length > 0 ? 580 : 100"
        :header-row-style="{color: 'dimgray'}"
        v-loading="loading"
        highlight-current-row
        :data="lossList"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="40" align="center" />
<!--        <el-table-column label="损失原因编码" show-overflow-tooltip width="170" prop="lossCode" />-->
        <el-table-column label="损失原因名称" width="170" show-overflow-tooltip prop="lossName"/>
        <el-table-column label="损失原因说明" prop="lossExplain" show-overflow-tooltip/>
        <el-table-column label="损失原因细则编码" prop="detailCode" show-overflow-tooltip width="170"/>
        <el-table-column label="损失原因细则名称" prop="detailName" show-overflow-tooltip width="170"/>
        <el-table-column label="角色" prop="roleName" show-overflow-tooltip width="200"/>
        <el-table-column label="订单核销单据状态名称" show-overflow-tooltip width="200">
					<template #default="scope">
							{{scope.row.roleName ? "待" +scope.row.roleName+"处理" : ""}}
					</template>
				</el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="150">
          <template #default="scope">
            <el-button
              v-hasPerm="['sys:loss:save']"
              type="primary"
              link
              size="small"
              @click.stop="openDialog(scope.row.id)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              v-hasPerm="['sys:loss:delete']"
              type="primary"
              link
              size="small"
              @click.stop="handleDelete(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
	  :close-on-click-modal="false"
      @close="closeDialog"
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="rules"
        label-width="170px"
      >
		<el-form-item label="损失原因" prop="lossCode">
<!--          <el-input v-model="formData.lossName" placeholder="请输入损失原因" clearable/>-->
          <dictionary v-model="formData.lossCode" :disabled="dialog.title === '修改损失细类'" type-code="loss" @change="changeLossCode" clearable/>
		</el-form-item>
        <el-form-item label="损失原因说明" prop="lossExplain">
          <el-input readonly v-model="formData.lossExplain" type="textarea" :rows="5" placeholder="请输入损失原因说明"/>
        </el-form-item>
        <el-form-item label="损失原因细则编码" prop="detailCode">
          <el-input v-model="formData.detailCode" disabled placeholder="请输入损失原因细则编码" clearable/>
        </el-form-item>
        <el-form-item label="损失原因细则名称" prop="detailName">
          <el-input v-model="formData.detailName" placeholder="请输入损失原因细则名称" clearable/>
        </el-form-item>
<!--        <el-form-item label="损失原因编码" prop="lossCode">-->
<!--            <el-input v-model="formData.lossCode" placeholder="请输入损失原因编码" clearable/>-->
<!--        </el-form-item>-->
        <el-form-item label="角色" prop="roleId">
          <el-select class="yz-el-select" v-model="formData.roleId" placeholder="请选择角色" @change="changeRole">
            <el-option
                    v-for="item in roleList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="订单核销单据状态名称" prop="orderStatusName">
          <el-input disabled v-model="formData.orderStatusName" placeholder="请输入订单核销单据状态名称" clearable/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入弹窗 -->
    <el-dialog
            v-model="importDialog.visible"
            :title="importDialog.title"
            width="600px"
            append-to-body
            :close-on-click-modal="false"
            @close="closeImportDialog"
    >
      <el-form label-width="80px">

        <el-form-item label="Excel">
          <el-upload
                  class="upload-demo"
                  action=""
                  drag
                  :auto-upload="false"
                  accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                  :file-list="excelFilelist"
                  :on-change="handleExcelChange"
                  :limit="1"
          >
            <el-icon class="el-icon--upload">
              <i-ep-upload-filled />
            </el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">xls/xlsx files</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleLossImport">确 定</el-button>
          <el-button @click="closeImportDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
